package com.megagoodsoftware.MediaShare;

import java.io.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.*;
import android.os.*;
import android.util.*;
import android.widget.RemoteViews;

import com.megagoodsoftware.smugmug.*;
import com.megagoodsoftware.smugmug.CountingHttpEntity.*;
import com.megagoodsoftware.smugmug.exceptions.*;
import com.megagoodsoftware.smugmug.util.*;

public class UploadService extends IntentService {

	private static final int IMAGE_MAX_SIZE = 200;
	private SmugMug sm;
	private NotificationManager mNotificationManager;
	private PendingIntent contentIntent;

	public UploadService() {
		super("UploadService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Bundle extras = intent.getExtras();
		SmugMugAccount account = (SmugMugAccount) intent
				.getParcelableExtra("SM_ACCOUNT");
		String album = intent.getStringExtra("SM_ALBUM");
		String passwd = intent.getStringExtra("SM_PASSWORD");
		String id = intent.getStringExtra("SM_ID");
        User user = new User(id,passwd);
        Intent tmpIntent = new Intent(this,	SmugMugPhotostreamActivity.class);
        tmpIntent.putExtra(SmugMugBundleHelper.EXTRA_ALBUM, album);
        tmpIntent.putExtra(SmugMugBundleHelper.EXTRA_USER, user);

		// This is who should be launched if the user selects our notification.
		contentIntent = PendingIntent.getActivity(this, 0, tmpIntent, 0);

		sm = ((MediaShareApp) getApplicationContext()).getSmugMugHandle();

		if (extras != null) {
			Object o = extras.get(Intent.EXTRA_STREAM);
			if (o instanceof Uri) {
				Uri target = (Uri) o;
				uploadURI(account, album, target);
			} else if (o instanceof ArrayList<?>) {
				ArrayList<?> uris = (ArrayList<?>) o;
				for (Iterator<?> it = uris.iterator(); it.hasNext();) {
					Uri target = (Uri) it.next();
					uploadURI(account, album, target);
				}
			}
		}
	}

	private void uploadURI(SmugMugAccount account, String album, Uri target) {
		final RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.custom_layout);
		boolean retVal;
		MediaShareFile file = new MediaShareFile(getContentResolver(), target);
		final Notification notification = new Notification(R.drawable.smugmug, 
				"SmugMug uploading!",// the text to display in the ticker
				System.currentTimeMillis()); // the timestamp for the
												// notification

		contentView.setProgressBar(R.id.custom_view_progress,
				Constants.PROGRESS_MAX, 0, false);
		contentView.setTextViewText(R.id.custom_view_text, "" + 0
				+ "% completed");
		Bitmap foo = decodeFile(file);
		if (foo == null)
			foo = BitmapFactory.decodeResource(getResources(), R.drawable.not_found_small_1);
		contentView
				.setImageViewBitmap(R.id.custom_view_image, foo);

		notification.contentView = contentView;
		notification.contentIntent = contentIntent;
		int returnedID = 0;
		mNotificationManager.notify((String) file.getName(), returnedID,
				notification);

		retVal = uploadTarget(target, account, album, notification);
		CharSequence text = null;
		if (retVal == true) {
			text = getText(R.string.success_file_upload);
			System.out.println("Upload Successful!");
		} else {
			text = getText(R.string.failure_file_upload);
			System.out.println("Upload Failed!");
		}
		Log.i(Constants.TAG, "uploadURI: filename: " + file.getName() + text);

		notification.contentView.setProgressBar(R.id.custom_view_progress,
				Constants.PROGRESS_MAX, Constants.PROGRESS_MAX, false);
		notification.contentView.setTextViewText(R.id.custom_view_text, file
				.getName()
				+ ": " + text);

		mNotificationManager.notify((String) file.getName(), returnedID,
				notification);
	}

	private boolean uploadTarget(Uri target, SmugMugAccount account,
			String album, final Notification notification) {
		final int returnedID = 0;
		InputStream md5is = null;
		InputStream in = null;
		try {
			final MediaShareFile file = new MediaShareFile(
					getContentResolver(), target);
			// need to open a separate input stream to get the md5sum
			md5is = file.openInputStream();
			in = file.openInputStream();
			System.out.println("file size = " + file.getSize());

			ProgressListener listener = new ProgressListener() {
				int notifyCounter = 0;

				@Override
				public void transferred(int num) {
					int percent = (int) (((float) num / file.getSize()) * 99);
					//Log.i(Constants.TAG, "uploadTarget: num: " + num + " percent: " +
							//		percent);

					if (notifyCounter % 30 == 0) {
						notification.contentView.setProgressBar(
								R.id.custom_view_progress,
								Constants.PROGRESS_MAX, percent, false);
						notification.contentView.setTextViewText(
								R.id.custom_view_text, "" + percent
										+ "% completed");
						mNotificationManager.notify((String) file.getName(), returnedID,
								notification);
				}
					notifyCounter++;
				}
			};

			sm.upload(listener, in, SmugMugUtil.getMd5Hash(md5is), sm
					.getAlbums(album).get(0), file.getName());
			return true;
		} catch (SmugMugConnectionError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmugMugFailedResponse e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmugMugInternalError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			Log.d(Constants.TAG, "Unexpected exception: " + e);
		} finally {
			try {
				md5is.close();
				in.close();
			} catch (IOException e) {
				Log.w(Constants.TAG, "Unable to close connection: " + e);
			}
		}
		return false;
	}

	private Bitmap decodeFile(MediaShareFile file) {
		Bitmap b = null;
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		try {
			BitmapFactory.decodeStream(file.openInputStream(), null, o);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int scale = 1;
		if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
			scale = 2 ^ (int) Math.ceil(Math.log(IMAGE_MAX_SIZE
					/ (double) Math.max(o.outHeight, o.outWidth))
					/ Math.log(0.5));
		}

		// Decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		try {
			b = BitmapFactory.decodeStream(file.openInputStream(), null, o2);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return b;
	}

}
